/*
 * Copyright 2009 Google Inc.
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *     http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */

package org.gtugs.web;

import org.gtugs.domain.Chapter;
import org.gtugs.domain.Event;
import org.gtugs.domain.Topic;
import org.gtugs.domain.User;
import org.gtugs.service.ChapterManager;
import org.gtugs.service.CountryManager;
import org.gtugs.service.EventManager;
import org.gtugs.service.security.AppEngineUserService;
import org.springframework.beans.propertyeditors.CustomBooleanEditor;
import org.springframework.beans.propertyeditors.CustomDateEditor;
import org.springframework.beans.propertyeditors.CustomNumberEditor;
import org.springframework.beans.propertyeditors.StringTrimmerEditor;
import org.springframework.validation.BindException;
import org.springframework.web.bind.ServletRequestDataBinder;
import org.springframework.web.servlet.mvc.SimpleFormController;
import org.springframework.web.servlet.ModelAndView;
import org.springframework.web.servlet.view.RedirectView;

import java.text.SimpleDateFormat;
import java.util.Calendar;
import java.util.Date;
import java.util.HashMap;
import java.util.Map;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

/**
 * @author jasonacooper@google.com (Jason Cooper)
 */
public class AddEventFormController extends SimpleFormController {

  private ChapterManager chapterManager;
  private CountryManager countryManager;
  private EventManager eventManager;

  @Override 
  protected void initBinder(HttpServletRequest request,
      ServletRequestDataBinder binder) throws Exception {
    binder.registerCustomEditor(String.class, new StringTrimmerEditor(false));
    binder.registerCustomEditor(Date.class, null, new CustomDateEditor(
        new SimpleDateFormat("MM/dd/yyyy"), false));
    binder.registerCustomEditor(Long.class, new CustomNumberEditor(Long.class,
        true));
    binder.registerCustomEditor(Boolean.class, new CustomBooleanEditor(true));
  }

  @Override
  @SuppressWarnings("unchecked")
  protected ModelAndView showForm(HttpServletRequest request,
      HttpServletResponse response, BindException errors) {
    Map<String, Object> map = new HashMap<String, Object>();
    String chapterId = request.getParameter("id");
    Map model = errors.getModel();

    AppEngineUserService userService = new AppEngineUserService();
    map.put("userService", userService);
    model.put("model", map);

    Chapter chapter = retrieveChapter(chapterId);

    if (chapter == null) {
      String errorText = "Failed to retrieve chapter with ID \"" + chapterId +
          "\" -- chapter not found.";
      model.put("errorText", errorText);

      return new ModelAndView("admin_error", model);
    }
    if (!hasAccess(userService, chapter)) {
      userService.setAfterLogoutEndpoint("/admin");

      String errorText = "You are not listed as an organizer for this " +
          "chapter. Please sign in with an organizer's account to access " +
          "this page.";
      model.put("errorText", errorText);

      return new ModelAndView("admin_error", model);
    }

    map.put("countries", countryManager.getCountries());
    map.put("chapter", chapter);

    return new ModelAndView(getFormView(), model);
  }

  @Override
  protected Object formBackingObject(HttpServletRequest request) throws
      ServletException {
    String chapterId = request.getParameter("id");
    Chapter chapter = retrieveChapter(chapterId);

    if (chapter == null) {
      return new Event();
    }

    Event event = new Event();
    event.setChapterId(chapter.getId());
    event.setStartDate(new Date());
    event.setStartTime("1900");
    event.setEndDate(new Date());
    event.setEndTime("2100");
    event.setCity(chapter.getCity());
    event.setState(chapter.getState());
    event.setCountry(chapter.getCountry());

    return event;
  }

  @Override
  protected void onBind(HttpServletRequest request, Object command)
      throws Exception {
    Event event = (Event) command;
    String endTime = event.getEndTime();
    String startTime = event.getStartTime();
    Calendar calendar = Calendar.getInstance();

    int endHour = Integer.parseInt(endTime.substring(0, 2));
    int endMinute = Integer.parseInt(endTime.substring(2, 4));
    int startHour = Integer.parseInt(startTime.substring(0, 2));
    int startMinute = Integer.parseInt(startTime.substring(2, 4));

    calendar.setTime(event.getStartDate());
    calendar.set(Calendar.HOUR_OF_DAY, startHour);
    calendar.set(Calendar.MINUTE, startMinute);
    event.setStartDate(calendar.getTime());

    calendar.setTime(event.getEndDate());
    calendar.set(Calendar.HOUR_OF_DAY, endHour);
    calendar.set(Calendar.MINUTE, endMinute);
    event.setEndDate(calendar.getTime());

    if (event.getOnAndroid()) {
      event.addTopic(Topic.ANDROID);
    }
    if (event.getOnGoogleAjaxApis()) {
      event.addTopic(Topic.GOOGLE_AJAX_APIS);
    }
    if (event.getOnGoogleAppEngine()) {
      event.addTopic(Topic.GOOGLE_APP_ENGINE);
    }
    if (event.getOnGoogleChromeExtensions()) {
      event.addTopic(Topic.GOOGLE_CHROME_EXTENSIONS);
    }
    if (event.getOnGoogleEarthApis()) {
      event.addTopic(Topic.GOOGLE_EARTH_APIS);
    }
    if (event.getOnGoogleMapsApis()) {
      event.addTopic(Topic.GOOGLE_MAPS_APIS);
    }
    if (event.getOnGoogleWaveApis()) {
      event.addTopic(Topic.GOOGLE_WAVE_APIS);
    }
    if (event.getOnGoogleWebToolkit()) {
      event.addTopic(Topic.GOOGLE_WEB_TOOLKIT);
    }
    if (event.getOnOpenSocial()) {
      event.addTopic(Topic.OPENSOCIAL);
    }
    if (event.getOnOther() && event.getCustomTopic() != null &&
        !event.getCustomTopic().equals("")) {
      event.addTopic(event.getCustomTopic());
    }
  }

  @Override
  public ModelAndView onSubmit(Object command) throws ServletException {
    Event cmd = (Event) command;
    Chapter chapter = retrieveChapter(cmd.getChapterId());
    AppEngineUserService userService = new AppEngineUserService();

    if (chapter == null) {
      String errorText = "Failed to update chapter with ID \"" +
          cmd.getChapterId() + "\" -- chapter not found.";

      return new ModelAndView("admin_error", "errorText", errorText);
    }
    if (!hasAccess(userService, chapter)) {
      String errorText = "You are not listed as an organizer for this " +
          "chapter. Please sign in with an organizer's account to access " +
          "this page.";

      return new ModelAndView("error", "errorText", errorText);
    }

    eventManager.storeEvent(cmd);

    return new ModelAndView(new RedirectView(getSuccessView() + "?id=" +
        chapter.getId() + "&t=events"));
  }

  public void setChapterManager(ChapterManager chapterManager) {
    this.chapterManager = chapterManager;
  }

  public void setCountryManager(CountryManager countryManager) {
    this.countryManager = countryManager;
  }

  public void setEventManager(EventManager eventManager) {
    this.eventManager = eventManager;
  }

  private Chapter retrieveChapter(String idString) {
    Long id = null;

    try {
      id = Long.parseLong(idString);
    } catch (NumberFormatException ex) {
      return null;
    }

    return retrieveChapter(id);
  }

  private Chapter retrieveChapter(Long id) {
    return chapterManager.getChapter(id);
  }

  private boolean hasAccess(AppEngineUserService userService, Chapter
      chapter) {
    if (userService.isUserAdmin()) {
      return true;
    }

    User user = userService.getUser();
    for (User administrator : chapter.getAdministrators()) {
      if (administrator.getEmail().equalsIgnoreCase(user.getEmail())) {
        return true;
      }
    }

    return false;
  }
}
